// src/main/java/com/mifan/security/CustomAccessDeniedHandler.java
package com.mifan.security;

import com.alibaba.fastjson.JSON;
import com.mifan.common.Results;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Results<Object> failure = Results.failure("暂无权限,请联系管理员");
        String string = JSON.toJSONString(failure);
        PrintWriter writer = response.getWriter();
        writer.write(string);
        writer.flush();
        writer.close();
    }
}